package org.ling.xuan.pannel;


import cn.hutool.core.util.StrUtil;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.JBPasswordField;
import com.intellij.ui.components.JBTextField;
import org.ling.xuan.entity.mo.EmailSetting;

import java.awt.*;

public class EmailSettingPanel extends JBPanel {
    private EmailSetting emailSetting;
    private ComboBox<String> type;
    private JBTextField hostTextField;
    private JBTextField portTextField;
    private JBTextField emailTextField;
    private JBPasswordField passwordTextField;
    private JBCheckBox sslCheckBox;


    public EmailSettingPanel(EmailSetting emailSetting) {
        this.emailSetting = emailSetting;
        if (this.emailSetting == null) {
            this.emailSetting = new EmailSetting();
        }
        initializeUI();
    }

    private void initializeUI() {
        setLayout(new GridLayout(7, 2));
        add(new JBLabel("Type:"));
        //"pop3", "imap" 暂不支持
        type = new ComboBox<>(new String[]{"smtp"});
        type.setSelectedIndex(0);
        add(type);
        add(new JBLabel("Host:"));
        add(hostTextField = new JBTextField());
        add(new JBLabel("Port:"));
        add(portTextField = new JBTextField());
        add(new JBLabel("Email:"));
        add(emailTextField = new JBTextField());
        add(new JBLabel("Password:"));
        add(passwordTextField = new JBPasswordField());
        add(new JBLabel("SSL:"));
        add(sslCheckBox = new JBCheckBox());
        if (StrUtil.isNotBlank(emailSetting.getType())) {
            type.setSelectedItem(emailSetting.getType());
        }
        hostTextField.setText(emailSetting.getHost());
        portTextField.setText(String.valueOf(emailSetting.getPort()));
        emailTextField.setText(emailSetting.getEmail());
        passwordTextField.setText(emailSetting.getPassword());
        sslCheckBox.setSelected(false);
        //懒得适配ssl.直接禁用了
        sslCheckBox.setEnabled(false);
    }


    public EmailSetting getSetting() {
        emailSetting.setType(type.getSelectedItem().toString());
        emailSetting.setHost(hostTextField.getText());
        emailSetting.setPort(Integer.parseInt(portTextField.getText()));
        emailSetting.setEmail(emailTextField.getText());
        emailSetting.setPassword(String.valueOf(passwordTextField.getPassword()));
        emailSetting.setSsl(sslCheckBox.isSelected());
        return emailSetting;
    }

}
